/**
 * 邮件发送任务列表页面
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Select,
  Tag,
  Popconfirm,
  message,
  Modal,
  Progress,
  Tooltip,
} from 'antd';
import {
  SendOutlined,
  EyeOutlined,
  StopOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { history } from '@umijs/max';
import type { ColumnsType } from 'antd/es/table';
import {
  getEmailTasks,
  getEmailTask,
  cancelEmailTask,
  type EmailTask,
  EmailTaskStatus,
} from '@/services/emailSend';

const { Search } = Input;
const { Option } = Select;

const EmailTasksPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<EmailTask[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<EmailTaskStatus | undefined>();
  const [detailVisible, setDetailVisible] = useState(false);
  const [selectedTask, setSelectedTask] = useState<EmailTask | null>(null);

  // 获取邮件任务列表
  const fetchEmailTasks = async () => {
    setLoading(true);
    try {
      const response = await getEmailTasks({
        page: current,
        size: pageSize,
        search: searchText || undefined,
        status: statusFilter,
      });
      setData(response.items);
      setTotal(response.total);
    } catch (error: any) {
      message.error(error.message || '获取邮件任务列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchEmailTasks();
  }, [current, pageSize, searchText, statusFilter]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
    setCurrent(1);
  };

  // 处理取消任务
  const handleCancelTask = async (taskId: string) => {
    try {
      await cancelEmailTask(taskId);
      message.success('任务取消成功');
      fetchEmailTasks();
    } catch (error: any) {
      message.error(error.message || '任务取消失败');
    }
  };

  // 查看任务详情
  const handleViewDetail = async (task: EmailTask) => {
    try {
      const taskDetail = await getEmailTask(task.id);
      setSelectedTask(taskDetail);
      setDetailVisible(true);
    } catch (error: any) {
      message.error(error.message || '获取任务详情失败');
    }
  };

  // 获取状态标签
  const getStatusTag = (status: EmailTaskStatus) => {
    const statusMap = {
      [EmailTaskStatus.PENDING]: { color: 'default', text: '等待中' },
      [EmailTaskStatus.RUNNING]: { color: 'processing', text: '发送中' },
      [EmailTaskStatus.COMPLETED]: { color: 'success', text: '已完成' },
      [EmailTaskStatus.FAILED]: { color: 'error', text: '失败' },
      [EmailTaskStatus.CANCELLED]: { color: 'warning', text: '已取消' },
    };
    const config = statusMap[status] || statusMap[EmailTaskStatus.PENDING];
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 计算进度
  const getProgress = (task: EmailTask) => {
    if (task.recipients_count === 0) return 0;
    return Math.round(((task.sent_count + task.failed_count) / task.recipients_count) * 100);
  };

  // 表格列定义
  const columns: ColumnsType<EmailTask> = [
    {
      title: '任务ID',
      dataIndex: 'id',
      key: 'id',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text.substring(0, 8)}...</span>
        </Tooltip>
      ),
    },
    {
      title: '邮件主题',
      dataIndex: 'subject',
      key: 'subject',
      ellipsis: true,
      render: (text: string) => (
        <Tooltip title={text}>
          <span>{text}</span>
        </Tooltip>
      ),
    },
    {
      title: '收件人数量',
      dataIndex: 'recipients_count',
      key: 'recipients_count',
      width: 100,
    },
    {
      title: '发送进度',
      key: 'progress',
      width: 150,
      render: (_, record: EmailTask) => {
        const progress = getProgress(record);
        return (
          <div>
            <Progress
              percent={progress}
              size="small"
              status={record.status === EmailTaskStatus.FAILED ? 'exception' : 'normal'}
            />
            <div style={{ fontSize: 12, color: '#666', marginTop: 2 }}>
              成功: {record.sent_count} / 失败: {record.failed_count}
            </div>
          </div>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: EmailTaskStatus) => getStatusTag(status),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (text: string) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record: EmailTask) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          {(record.status === EmailTaskStatus.PENDING || record.status === EmailTaskStatus.RUNNING) && (
            <Popconfirm
              title="确定要取消这个任务吗？"
              onConfirm={() => handleCancelTask(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Tooltip title="取消任务">
                <Button type="text" danger icon={<StopOutlined />} />
              </Tooltip>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '邮件发送任务',
        breadcrumb: {},
      }}
    >
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space wrap>
            <Search
              placeholder="搜索邮件主题"
              allowClear
              style={{ width: 300 }}
              onSearch={handleSearch}
            />
            <Select
              placeholder="选择状态"
              allowClear
              style={{ width: 120 }}
              value={statusFilter}
              onChange={setStatusFilter}
            >
              <Option value={EmailTaskStatus.PENDING}>等待中</Option>
              <Option value={EmailTaskStatus.RUNNING}>发送中</Option>
              <Option value={EmailTaskStatus.COMPLETED}>已完成</Option>
              <Option value={EmailTaskStatus.FAILED}>失败</Option>
              <Option value={EmailTaskStatus.CANCELLED}>已取消</Option>
            </Select>
            <Button icon={<ReloadOutlined />} onClick={fetchEmailTasks}>
              刷新
            </Button>
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={() => history.push('/emails/send')}
            >
              发送邮件
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size || 10);
            },
          }}
        />
      </Card>

      {/* 任务详情弹窗 */}
      <Modal
        title={`任务详情 - ${selectedTask?.id?.substring(0, 8)}...`}
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)}>
            关闭
          </Button>,
        ]}
        width={800}
      >
        {selectedTask && (
          <div>
            <div style={{ marginBottom: 16 }}>
              <strong>任务ID：</strong>{selectedTask.id}
            </div>
            <div style={{ marginBottom: 16 }}>
              <strong>邮件主题：</strong>{selectedTask.subject}
            </div>
            <div style={{ marginBottom: 16 }}>
              <strong>状态：</strong>{getStatusTag(selectedTask.status)}
            </div>
            <div style={{ marginBottom: 16 }}>
              <strong>收件人数量：</strong>{selectedTask.recipients_count}
            </div>
            <div style={{ marginBottom: 16 }}>
              <strong>发送成功：</strong>{selectedTask.sent_count}
            </div>
            <div style={{ marginBottom: 16 }}>
              <strong>发送失败：</strong>{selectedTask.failed_count}
            </div>
            <div style={{ marginBottom: 16 }}>
              <strong>发送方式：</strong>
              {selectedTask.send_immediately ? '立即发送' : '定时发送'}
            </div>
            {selectedTask.scheduled_time && (
              <div style={{ marginBottom: 16 }}>
                <strong>定时时间：</strong>
                {new Date(selectedTask.scheduled_time).toLocaleString()}
              </div>
            )}
            <div style={{ marginBottom: 16 }}>
              <strong>创建时间：</strong>
              {new Date(selectedTask.created_at).toLocaleString()}
            </div>
            {selectedTask.started_at && (
              <div style={{ marginBottom: 16 }}>
                <strong>开始时间：</strong>
                {new Date(selectedTask.started_at).toLocaleString()}
              </div>
            )}
            {selectedTask.completed_at && (
              <div style={{ marginBottom: 16 }}>
                <strong>完成时间：</strong>
                {new Date(selectedTask.completed_at).toLocaleString()}
              </div>
            )}
            {selectedTask.error_message && (
              <div style={{ marginBottom: 16 }}>
                <strong>错误信息：</strong>
                <div style={{ 
                  marginTop: 8, 
                  padding: 8, 
                  backgroundColor: '#fff2f0',
                  border: '1px solid #ffccc7',
                  borderRadius: 4,
                }}>
                  {selectedTask.error_message}
                </div>
              </div>
            )}
          </div>
        )}
      </Modal>
    </PageContainer>
  );
};

export default EmailTasksPage;
